'''
电话簿
姓名,电话号码,地址
tom,123456,西安

功能：
1）添加信息
2）修改信息：根据姓名修改电话号码
3）删除：删除叫张三的整行信息
4）查：查看李四的整行信息
5）查看所有的人员信息
'''
import csv
import os
#主要实现逻辑再change函数，其余函数的功能实现均根据change修改
file= "PhoneNumber.csv"
operation_file= "Operation.csv"  #改和查时，将数据复制到operation，处理完再重新覆盖file


def initialize_csv_files():
    '''
    用于检测文件是否存在，不存在则创建，存在则忽略
    :return:
    '''
    files_to_init = [
        "PhoneNumber.csv",
        "Operation.csv"
    ]
    fieldnames = ['name', 'phone', 'address']
    for filename in files_to_init:
        if not os.path.isfile(filename):  # 如果文件不存在
            with open(filename, mode='w', newline='', encoding='utf-8') as f:
                writer = csv.DictWriter(f, fieldnames=fieldnames)
                writer.writeheader()  # 写入表头
        else:
            break





def add(name,phone,address):
    with open(f'{file}','a',newline='',encoding='utf-8') as f:
        writer1 = csv.DictWriter(f, fieldnames=['name', 'phone', 'address'])
        writer1.writerow({
            "name": name,
            "phone": phone,
            "address": address
        })
    with open(f'{operation_file}','w+',newline='',encoding='utf-8') as o:
        writer_o = csv.DictWriter(o, fieldnames=['name', 'phone', 'address'])
        writer_o.writeheader()

def change(name,newphone):
    '''
    创建一个用于存储源数据的备份文件，定义用于存储新数据的replace，根据name进行遍历，
    判断是否为目标，写入到备份表，得到目标时，获取目标address，赋值给replace[]写入备份表
    循环执行结束，关闭两个文件，交换文件名称。
    '''
    with open(f'{file}','r+',newline='',encoding='utf-8') as f:
        with open(f'{operation_file}','w+',newline='',encoding='utf-8') as o:
            reader_f = csv.DictReader(f)#读取源数据
            writer_o = csv.DictWriter(o, fieldnames=['name', 'phone', 'address'])
            replace={
                "name": name,
                "phone": newphone,
                "address": None
            }
            for row in reader_f:#遍历读取源文件
                if row['name']==name:#寻找目标信息
                    replace['address']=row['address']
                    writer_o.writerow(replace)#写入更新后的数据
                    print('交换成功')
                    continue
                writer_o.writerow(row)#写入其他
    #交换名称
    temp='replace.csv'
    os.rename(operation_file,temp)#o-->t
    os.rename(file,operation_file)#f-->o
    os.rename(temp,file)#t-->f

def delete(name):
    '''
    创建一个用于存储源数据的备份文件，定义用于存储新数据的replace，根据name进行遍历，
    判断是否为目标，写入到备份表，得到目标时，跳出循环
    循环执行结束，关闭两个文件，交换文件名称。
    '''
    with open(f'{file}','r+',newline='',encoding='utf-8') as f:
        with open(f'{operation_file}','w+',newline='',encoding='utf-8') as o:
            reader_f = csv.DictReader(f)#读取源数据
            writer_o = csv.DictWriter(o, fieldnames=['name', 'phone', 'address'])
            writer_o.writeheader()
            replace={
                "name": name,
                "phone": None,
                "address": None

            }
            for row in reader_f:#遍历读取源文件
                if row['name']==name:#寻找目标信息
                    # replace['address']=row['address']
                    # replace['phone']=row['phone']
                    # writer_o.writerow(replace)#写入更新后的数据
                    print('删除成功')
                    continue
                writer_o.writerow(row)#写入其他
    #交换名称
    temp='replace.csv'
    os.rename(operation_file,temp)#o-->t
    os.rename(file,operation_file)#f-->o
    os.rename(temp,file)#t-->f


def get_by_name(name):
    with open(f'{file}','r+',newline='',encoding='utf-8') as f:
            reader_f = csv.DictReader(f)#读取源数据
            replace={
                "name": name,
                "phone": None,
                "address": None
            }
            for row in reader_f:#遍历读取源文件
                if row['name']==name:#寻找目标信息
                    replace['address']=row['address']
                    replace['phone']=row['phone']
                    print(f'{replace["name"]} {replace["phone"]} {replace["address"]}')
                    break
                return print('查无此人')

def get_all():
    with open(f'{file}','r+',newline='',encoding='utf-8') as f:
            reader_f = csv.DictReader(f)#读取源数据
            replace={
                "name": None,
                "phone": None,
                "address": None
            }
            for row in reader_f:#遍历读取源文件
                replace['address'] = row['address']
                replace['phone'] = row['phone']
                replace['name'] = row['name']
                print(f'{replace["name"]:<13} {replace["phone"]:<13} {replace["address"]:<13}')
            return print('输出完毕')

# 主方法
def main():
    print("-----欢迎来到xx电话簿系统------")

    while True:
        print("---1) 添加信息---")
        print("---2) 根据姓名修改信息---")
        print("---3) 删除信息---")
        print("---4) 查看单个人员信息---")
        print("---5) 查看所有人员信息---")
        print("---6) 退出---")

        num = int(input("请输入你的操作:"))
        if num ==1:
            print("请输入以下信息")
            name= input("姓名:")
            phone = input("电话：")
            address= input("地址：")
            add(name,phone,address)
        elif num==2:
            print("需要提供修改的姓名和修改后的电话号码")
            name = input("姓名：")
            newphone= input("电话号码：")
            change(name,newphone)
        elif num == 3:
            print("提供删除目标姓名")
            name = input("姓名：")
            delete(name)
        elif num == 4:
            print("提供查询目标姓名")
            name = input("姓名：")
            get_by_name(name)
        elif num == 5:
            get_all()
        else:
            print("退出系统")
            break

if __name__ == '__main__':
    initialize_csv_files()
    main()